package com.example.smartcity.ui.person.login

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity.databinding.ActivityFeedBackBinding
import com.example.smartcity.logic.utils.BaseActivity
import com.example.smartcity.ui.person.Adapter.FeedBackRecyclerViewAdapter
import com.example.smartcity.ui.person.model.FeedEntity
import kotlin.math.log

class FeedBackActivity : BaseActivity() {

    private val viewModel by lazy {
        ViewModelProvider(this)[FeedBackActivityViewModel::class.java]
    }

    private lateinit var adapter: FeedBackRecyclerViewAdapter
    val array = ArrayList<FeedEntity>()
    /**
     * 更新列表数据
     */
    override fun onStart() {
        super.onStart()
        setAdapter()
    }

    private lateinit var mBinding: ActivityFeedBackBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityFeedBackBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        title = "意见反馈"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 添加反馈意见
        mBinding.fab.setOnClickListener {
            startActivity(Intent(this, FeedBackActivityAdd::class.java))
        }

        // adapter
        setAdapter()
    }

    private fun setAdapter() {
        // 设置适配器
        val layout = LinearLayoutManager(this)
        mBinding.FeedBackRecyclerView.layoutManager = layout
        adapter = FeedBackRecyclerViewAdapter(array)
        mBinding.FeedBackRecyclerView.adapter = adapter

        getSharedPreferences("token", MODE_PRIVATE).apply {
            // 装入token数据
            viewModel.feedback(this.getString("token","").toString())
        }
        // 获取数据
        viewModel.feedbackDataLIve.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if(body != null){
                viewModel.feedbackList.clear()
                viewModel.feedbackList.addAll(body)
            }

            // 填充数据
            for (i in viewModel.feedbackList){
                if (array.size < viewModel.feedbackList.size){
                    array.add(FeedEntity(i.title,i.content, i.createTime))
                    // 刷新数据
                    adapter.notifyItemChanged(array.size)
                }
            }
        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 销毁
        this.finish()
        return super.onOptionsItemSelected(item)
    }
}